package cn.amossun.starter.mybatis.data.security.interceptor;

import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import cn.amossun.starter.mybatis.data.security.rewrite.EncryptPreParameterRewriter;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.sql.Statement;
import java.util.List;

/**
 * @description:
 * @author: Amos.Sun
 * @DateTime: 2020/03/08 15:23
 **/
@Slf4j
@Intercepts({
        @Signature(type = StatementHandler.class, method = "parameterize", args = Statement.class)
})
@AllArgsConstructor
public class StatementHandlerInterceptor implements Interceptor {

    private final EncryptPreParameterRewriter encryptRewriter;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object target = PluginUtils.realTarget(invocation.getTarget());
        MetaObject metaObject = SystemMetaObject.forObject(target);
        Object parameterObject = metaObject.getValue("delegate.boundSql.parameterObject");

        //mybatis 对象为java Bean时

        //mybatis 对象为Statement代理 或 Wrapper时
        String sql = (String) metaObject.getValue("delegate.boundSql.sql");
        List<ParameterMapping> parameterMappings = (List<ParameterMapping>) metaObject.getValue("delegate.boundSql.parameterMappings");

        encryptRewriter.rewrite(sql, parameterMappings, parameterObject);
        return invocation.proceed();
    }

}
